package com.common;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by Administrator on 2018/5/25.
 */
public class CacheUtils {

    private Map<String, Object> map =  new ConcurrentHashMap<>();

    private volatile static CacheUtils cacheUtils = null;

    private CacheUtils() {

    }

    public static CacheUtils getInstance() {
        if (cacheUtils == null) {
            synchronized (CacheUtils.class) {
                if (cacheUtils == null) {
                    cacheUtils = new CacheUtils();
                }
            }
        }
        return cacheUtils;
    }

    /**
     * 根据key缓存value
     * @param key
     * @return
     */
    public Object getValue(String key) {
        return map.get(key);
    }

    /**
     * 设置缓存
     * ConcurrentHashMap put自带原子性
     * @param key
     * @param value
     * @return
     */
    public Map<String, Object> setCache(String key, Object value) {
        map.put(key, value);
        return map;
    }

    /**
     * 判断缓存是否存在
     * <pre>false:不存在该key;true:存在该key</pre>
     * @param key
     * @return
     */
    public boolean isExist(String key) {
        return map.containsKey(key);
    }

    /**
     *
     * @param key
     */
    public void remove(String key) {
        if(isExist(key)){
            map.remove(key);
        }
    }
    /**
     * 返回map对象
     * @return
     */
    public  Map<String, Object> getLocalMap(){
        return map;
    }


}
